#include "Game.hh" // 包含游戏头文件，定义了Game类和相关功能 / Include Game header, defines Game class and related functions
#include <iostream> // 包含输入输出库，用于显示信息和读取用户输入 / Include input-output library for displaying info and reading user input
#include <sstream> // 包含字符串流库，用于将数字转换为文本 / Include string stream library for converting numbers to text
#include <string> // 包含字符串库，用于处理文本数据 / Include string library for handling text data

// 构造函数：创建游戏对象，初始化所有变量并让用户选择游戏模式 / Constructor: Creates game object, initializes all variables, and lets user choose game mode
Game::Game() : player(nullptr), currentRoom(nullptr), gameOver(false), showPlayerStatus(true), showInventory(true), stepsToEnd(0), inVillage(false), x(0), y(0), turnCount(0) {
    std::cout << "———— Game Mode Selection ————\n";
    std::cout << "0. Survival Mode - Normal adventure, defeat the Ender Dragon\n";
    std::cout << "1. Creative Mode - Invincible, with powerful items\n";
    std::cout << "2. Load Game - Load from save file\n";
    std::cout << "Enter mode (0-2): ";

    std::string input;
    int mode;
    while (true) {
        std::getline(std::cin, input);
        if (validateInput(input, mode, 2)) break;
        std::cout << "Invalid input! Please enter a number between 0 and 2: ";
    }

    if (mode == 2) {
        loadGame();
    } else {
        initializeGame(mode);
    }
}

// 析构函数：当游戏对象销毁时，清理所有动态分配的内存 / Destructor: When game object is destroyed, clean up all dynamically allocated memory
Game::~Game() {
    delete player;
    for (Room* room : rooms) {
        delete room;
    }
    if (currentRoom != rooms[0]) delete currentRoom;
}

// 辅助函数：将文本居中并用横杠（-）填充两侧 / Helper function: Center text and fill both sides with dashes (-)
std::string centerWithDashes(const std::string& text, int totalWidth) {
    int textLength = text.length();
    int dashesNeeded = totalWidth - textLength;
    int leftDashes = dashesNeeded / 2;
    int rightDashes = dashesNeeded - leftDashes;
    return std::string(leftDashes, '-') + text + std::string(rightDashes, '-');
}

// 辅助函数：将内容填充到指定宽度，确保界面整齐 / Helper function: Pad content to a specific width to keep the interface neat
std::string padContent(const std::string& content, int width) {
    std::string result = content;
    if (result.length() > width) {
        result = result.substr(0, width);
    } else {
        result += std::string(width - result.length(), ' ');
    }
    return result;
}

// 显示游戏界面：绘制游戏的整个画面，包括位置、敌人、物品等 / Display game interface: Draw the entire game screen, including location, enemies, items, etc.
void Game::displayInterface() {
    clearScreen();
    const int WIDTH = 78;
    const std::string BORDER = std::string(80, '-');

    std::cout << BORDER << "\n";
    std::string title = centerWithDashes(" Minecraft RPG ", WIDTH);
    std::cout << "| " << title << " |\n";

    std::string location = "Location: " + currentRoom->getDescription() + " (Coords: " + std::to_string(x) + ", " + std::to_string(y) + ")";
    std::cout << "| " << padContent(location, WIDTH) << " |\n";
    std::cout << "| " << padContent("Quest: Travel south to find The End and defeat the Ender Dragon", WIDTH) << " |\n";
    if (inVillage) {
        std::cout << "| " << padContent("Status: In a village, safe", WIDTH) << " |\n";
    }
    std::cout << "| " << padContent("", WIDTH) << " |\n";

    std::cout << "| " << centerWithDashes(" Messages ", WIDTH) << " |\n";
    if (messageLog.empty()) {
        std::cout << "| " << padContent("- None", WIDTH) << " |\n";
    } else {
        for (const auto& msg : messageLog) {
            std::string formattedMsg = "- " + msg;
            while (formattedMsg.length() > WIDTH) {
                std::cout << "| " << padContent(formattedMsg.substr(0, WIDTH), WIDTH) << " |\n";
                formattedMsg = "  " + formattedMsg.substr(WIDTH);
            }
            std::cout << "| " << padContent(formattedMsg, WIDTH) << " |\n";
        }
    }
    std::cout << "| " << padContent("", WIDTH) << " |\n";

    std::cout << "| " << centerWithDashes(" Enemies ", WIDTH) << " |\n";
    auto& enemies = currentRoom->getEnemies();
    if (enemies.empty() || inVillage) {
        std::cout << "| " << padContent("- None", WIDTH) << " |\n";
    } else {
        for (size_t i = 0; i < enemies.size(); ++i) {
            std::string enemyStr = "- " + std::to_string(i + 1) + ". " + enemies[i]->toString();
            while (enemyStr.length() > WIDTH) {
                std::cout << "| " << padContent(enemyStr.substr(0, WIDTH), WIDTH) << " |\n";
                enemyStr = "    " + enemyStr.substr(WIDTH);
            }
            std::cout << "| " << padContent(enemyStr, WIDTH) << " |\n";
        }
    }
    std::cout << "| " << padContent("", WIDTH) << " |\n";

    std::cout << "| " << centerWithDashes(" Items ", WIDTH) << " |\n";
    auto& items = currentRoom->getItems();
    if (items.empty()) {
        std::cout << "| " << padContent("- None", WIDTH) << " |\n";
    } else {
        for (size_t i = 0; i < items.size(); ++i) {
            std::string bonus = "";
            if (items[i]->attackBonus > 0) bonus = " (+" + std::to_string(items[i]->attackBonus) + " Attack)";
            else if (items[i]->defenseBonus > 0) bonus = " (+" + std::to_string(items[i]->defenseBonus) + " Defense)";
            else if (items[i]->healthBonus > 0) bonus = " (+" + std::to_string(items[i]->healthBonus) + " Health)";
            std::string itemStr = "- " + std::to_string(i + 1) + ". " + items[i]->name + bonus;
            while (itemStr.length() > WIDTH) {
                std::cout << "| " << padContent(itemStr.substr(0, WIDTH), WIDTH) << " |\n";
                itemStr = "    " + itemStr.substr(WIDTH);
            }
            std::cout << "| " << padContent(itemStr, WIDTH) << " |\n";
        }
    }
    std::cout << "| " << padContent("", WIDTH) << " |\n";

    if (showInventory) {
        std::cout << "| " << centerWithDashes(" Inventory ", WIDTH) << " |\n";
        const auto& inventory = player->getInventory();
        if (inventory.empty()) {
            std::cout << "| " << padContent("- Empty", WIDTH) << " |\n";
        } else {
            for (size_t i = 0; i < inventory.size(); ++i) {
                std::string bonus = "";
                if (inventory[i]->attackBonus > 0) bonus = " (+" + std::to_string(inventory[i]->attackBonus) + " Attack)";
                else if (inventory[i]->defenseBonus > 0) bonus = " (+" + std::to_string(inventory[i]->defenseBonus) + " Defense)";
                else if (inventory[i]->healthBonus > 0) bonus = " (+" + std::to_string(inventory[i]->healthBonus) + " Health)";
                std::string invStr = "- " + std::to_string(i + 1) + ". " + inventory[i]->name + bonus;
                while (invStr.length() > WIDTH) {
                    std::cout << "| " << padContent(invStr.substr(0, WIDTH), WIDTH) << " |\n";
                    invStr = "    " + invStr.substr(WIDTH);
                }
                std::cout << "| " << padContent(invStr, WIDTH) << " |\n";
            }
        }
        std::string equipStr = "Equipment: Weapon: " + player->getEquippedWeapon() + " | Armor: " + player->getEquippedArmor();
        std::cout << "| " << padContent(equipStr, WIDTH) << " |\n";
        std::cout << "| " << padContent("", WIDTH) << " |\n";
    }

    if (showPlayerStatus) {
        std::cout << "| " << centerWithDashes(" Player ", WIDTH) << " |\n";
        std::string playerStr = player->toString();
        while (playerStr.length() > WIDTH) {
            std::cout << "| " << padContent(playerStr.substr(0, WIDTH), WIDTH) << " |\n";
            playerStr = "  " + playerStr.substr(WIDTH);
        }
        std::cout << "| " << padContent(playerStr, WIDTH) << " |\n";
        std::cout << "| " << padContent("", WIDTH) << " |\n";
    }

    std::cout << "| " << centerWithDashes(" Actions ", WIDTH) << " |\n";
    if (!inVillage) {
        std::vector<std::string> actions = {
            "1. North - Move north",
            "2. South - Move south",
            "3. East - Move east",
            "4. West - Move west",
            "5. Pickup - Pick up an item",
            "6. Attack - Attack an enemy",
            "7. Equip/Use - Equip or use an item",
            "8. Save - Save game",
            "9. Exit - End game",
            "10. Toggle Status - Show/hide player status",
            "11. Toggle Inventory - Show/hide inventory"
        };
        for (const auto& action : actions) {
            std::cout << "| " << padContent(action, WIDTH) << " |\n";
        }
    } else {
        std::vector<std::string> actions = {
            "1. Trade - Trade with villager",
            "2. Rest - Restore health",
            "3. Leave - Leave village"
        };
        for (const auto& action : actions) {
            std::cout << "| " << padContent(action, WIDTH) << " |\n";
        }
    }

    std::cout << BORDER << "\n";
    std::cout << "Enter choice: ";
}

// 处理用户输入：根据用户选择的动作执行相应操作 / Handle user input: Perform actions based on user's chosen option
bool Game::handleInput() {
    if (!player->isAlive()) { // 如果玩家已死亡 / If player is dead
        addMessage("[Turn " + std::to_string(turnCount) + "] You are dead and cannot act!"); // 添加消息：你已死亡，无法行动 / Add message: You are dead, cannot act
        gameOver = true; // 确保游戏结束 / Ensure game is over
        return false; // 停止处理输入 / Stop processing input
    }
    std::string input; // 定义字符串变量存储用户输入 / Define string variable to store user input
    int choice; // 定义整数变量存储用户选择的动作编号 / Define integer variable to store chosen action number
    int maxChoice = inVillage ? 3 : 11; // 设置最大动作编号（村庄3个，普通11个） / Set max action number (3 in village, 11 normally)
    while (true) { // 进入循环，直到用户输入有效数字 / Enter loop until user enters valid number
        std::getline(std::cin, input); // 读取用户输入的整行 / Read entire line of user input
        if (validateInput(input, choice, maxChoice)) break; // 如果输入有效，退出循环 / If input is valid, exit loop
        std::cout << "Invalid input! Please enter a number between 1 and " << maxChoice << ": "; // 提示输入无效，要求重新输入 / Prompt invalid input, ask to retry
    }

    incrementTurnCount(); // 增加回合计数，表示玩家完成一次操作 / Increment turn count, indicating player completed an action
    Room* oldRoom = currentRoom; // 保存当前房间指针，以便稍后清理 / Save current room pointer for later cleanup
    messageLog.clear(); // 清空消息日志，准备记录新事件 / Clear message log to record new events

    if (inVillage) { // 如果玩家在村庄 / If player is in a village
        if (choice == 1) tradeWithVillager(); // 选项1：调用交易函数 / Option 1: Call trade function
        else if (choice == 2) restInVillage(); // 选项2：调用休息函数 / Option 2: Call rest function
        else if (choice == 3) { // 选项3：离开村庄 / Option 3: Leave village
            inVillage = false; // 设置玩家不在村庄 / Set player as not in village
            addMessage("[Turn " + std::to_string(turnCount) + "] You left the village."); // 记录离开村庄的消息 / Log message for leaving village
        }
        return true; // 返回true，继续游戏循环 / Return true to continue game loop
    }

    switch (choice) { // 根据用户选择的动作编号执行不同操作 / Execute different actions based on chosen number
        case 1: // 选项1：向北移动 / Option 1: Move north
            y++; // Y坐标加1（向上移动） / Increment Y coordinate (move up)
            currentRoom = new Room(getRoomDescription(x, y)); // 创建新房间，基于新坐标 / Create new room based on new coordinates
            addMessage("[Turn " + std::to_string(turnCount) + "] You moved north to " + currentRoom->getDescription()); // 记录移动消息 / Log movement message
            stepsToEnd--; // 减少到达The End的步数 / Decrease steps to The End
            spawnEnemies(); // 随机生成敌人 / Spawn enemies randomly
            triggerRandomEvent(); // 触发随机事件（比如发现物品） / Trigger random event (e.g., find item)
            updateEnemySkills(); // 更新敌人技能（比如Creeper爆炸倒计时） / Update enemy skills (e.g., Creeper explosion countdown)
            break; // 结束此选项 / End this option
        case 2: // 选项2：向南移动 / Option 2: Move south
            y--; // Y坐标减1（向下移动） / Decrement Y coordinate (move down)
            stepsToEnd--; // 减少到达The End的步数 / Decrease steps to The End
            if (stepsToEnd <= 0) { // 如果步数耗尽，进入The End / If steps are exhausted, enter The End
                currentRoom = rooms[0]; // 设置当前房间为The End / Set current room to The End
                addMessage("[Turn " + std::to_string(turnCount) + "] You moved south to The End, the Ender Dragon's domain!"); // 记录进入The End的消息 / Log message for entering The End
            } else { // 否则，进入普通新房间 / Otherwise, enter a normal new room
                currentRoom = new Room(getRoomDescription(x, y)); // 创建新房间 / Create new room
                addMessage("[Turn " + std::to_string(turnCount) + "] You moved south to " + currentRoom->getDescription()); // 记录移动消息 / Log movement message
            }
            spawnEnemies(); // 随机生成敌人 / Spawn enemies randomly
            triggerRandomEvent(); // 触发随机事件 / Trigger random event
            updateEnemySkills(); // 更新敌人技能 / Update enemy skills
            break; // 结束此选项 / End this option
        case 3: // 选项3：向东移动 / Option 3: Move east
            x++; // X坐标加1（向右移动） / Increment X coordinate (move right)
            currentRoom = new Room(getRoomDescription(x, y)); // 创建新房间 / Create new room
            addMessage("[Turn " + std::to_string(turnCount) + "] You moved east to " + currentRoom->getDescription()); // 记录移动消息 / Log movement message
            stepsToEnd--; // 减少到达The End的步数 / Decrease steps to The End
            spawnEnemies(); // 随机生成敌人 / Spawn enemies randomly
            triggerRandomEvent(); // 触发随机事件 / Trigger random event
            updateEnemySkills(); // 更新敌人技能 / Update enemy skills
            break; // 结束此选项 / End this option
        case 4: // 选项4：向西移动 / Option 4: Move west
            x--; // X坐标减1（向左移动） / Decrement X coordinate (move left)
            currentRoom = new Room(getRoomDescription(x, y)); // 创建新房间 / Create new room
            addMessage("[Turn " + std::to_string(turnCount) + "] You moved west to " + currentRoom->getDescription()); // 记录移动消息 / Log movement message
            stepsToEnd--; // 减少到达The End的步数 / Decrease steps to The End
            spawnEnemies(); // 随机生成敌人 / Spawn enemies randomly
            triggerRandomEvent(); // 触发随机事件 / Trigger random event
            updateEnemySkills(); // 更新敌人技能 / Update enemy skills
            break; // 结束此选项 / End this option
        case 5: // 选项5：拾取物品 / Option 5: Pick up item
            {
                auto& items = currentRoom->getItems(); // 获取当前房间的物品列表 / Get list of items in current room
                if (!items.empty()) { // 如果房间有物品 / If room has items
                    Item* item = items.back(); // 获取最后一个物品 / Get the last item
                    player->addToInventory(item); // 将物品添加到玩家背包 / Add item to player's inventory
                    addMessage("[Turn " + std::to_string(turnCount) + "] You picked up " + item->name + "!"); // 记录拾取消息 / Log pickup message
                    items.pop_back(); // 从房间移除该物品 / Remove item from room
                } else { // 如果房间没有物品 / If room has no items
                    addMessage("[Turn " + std::to_string(turnCount) + "] No items to pick up here!"); // 记录无物品消息 / Log no items message
                }
            }
            break; // 结束此选项 / End this option
        case 6: // 选项6：攻击敌人 / Option 6: Attack enemy
            {
                auto& enemies = currentRoom->getEnemies(); // 获取当前房间的敌人列表 / Get list of enemies in current room
                if (enemies.empty()) { // 如果没有敌人 / If no enemies
                    addMessage("[Turn " + std::to_string(turnCount) + "] No enemies here!"); // 记录无敌人消息 / Log no enemies message
                } else { // 如果有敌人 / If there are enemies
                    std::cout << "Select target:\n"; // 提示用户选择攻击目标 / Prompt user to select attack target
                    for (size_t i = 0; i < enemies.size(); ++i) { // 遍历敌人列表 / Loop through enemy list
                        std::cout << i + 1 << ". " << enemies[i]->getName() << "\n"; // 显示敌人编号和名字 / Display enemy number and name
                    }
                    std::cout << "Enter target number: "; // 提示输入目标编号 / Prompt for target number
                    int target; // 定义变量存储目标编号 / Define variable to store target number
                    while (true) { // 进入循环，直到输入有效 / Enter loop until valid input
                        std::getline(std::cin, input); // 读取用户输入 / Read user input
                        if (validateInput(input, target, enemies.size())) break; // 如果输入有效，退出循环 / If input is valid, exit loop
                        std::cout << "Invalid input! Please enter a number between 1 and " << enemies.size() << ": "; // 提示重新输入 / Prompt to retry
                    }
                    Character* enemy = static_cast<Character*>(enemies[target - 1]); // 获取目标敌人 / Get target enemy
                    player->attack(*enemy); // 玩家攻击目标敌人 / Player attacks target enemy
                    if (!enemy->isAlive()) { // 如果敌人死亡 / If enemy is dead
                        addMessage("[Turn " + std::to_string(turnCount) + "] You defeated " + enemy->getName() + "!"); // 记录击败消息 / Log defeat message
                        int dropChance = rand() % 100; // 随机生成0-99的掉落概率 / Generate random drop chance (0-99)
                        if (enemy->getName() == "Creeper" && dropChance < 50) { // 如果是Creeper且50%概率 / If Creeper and 50% chance
                            player->addToInventory(new Item("Gunpowder", "Creeper's drop", 0, 0, 0)); // 添加火药 / Add Gunpowder
                            addMessage("[Turn " + std::to_string(turnCount) + "] Creeper dropped Gunpowder!"); // 记录掉落消息 / Log drop message
                        } else if (enemy->getName() == "Skeleton" && dropChance < 60) { // 如果是Skeleton且60%概率 / If Skeleton and 60% chance
                            player->addToInventory(new Item("Bone", "Skeleton's drop", 0, 0, 0)); // 添加骨头 / Add Bone
                            addMessage("[Turn " + std::to_string(turnCount) + "] Skeleton dropped a Bone!"); // 记录掉落消息 / Log drop message
                        } else if (enemy->getName() == "Pillager" && dropChance < 40) { // 如果是Pillager且40%概率 / If Pillager and 40% chance
                            player->addToInventory(new Item("Crossbow", "Pillager's weapon", 10, 0, 0)); // 添加弩 / Add Crossbow
                            addMessage("[Turn " + std::to_string(turnCount) + "] Pillager dropped a Crossbow!"); // 记录掉落消息 / Log drop message
                        } else if (enemy->getName() == "Witch" && dropChance < 70) { // 如果是Witch且70%概率 / If Witch and 70% chance
                            player->addToInventory(new Item("Glass Bottle", "Witch's drop", 0, 0, 0)); // 添加玻璃瓶 / Add Glass Bottle
                            addMessage("[Turn " + std::to_string(turnCount) + "] Witch dropped a Glass Bottle!"); // 记录掉落消息 / Log drop message
                        } else if (enemy->getName() == "Ender Dragon" && dropChance < 100) { // 如果是Ender Dragon且100%概率 / If Ender Dragon and 100% chance
                            player->addToInventory(new Item("Dragon Egg", "Ender Dragon's relic", 0, 0, 0)); // 添加龙蛋 / Add Dragon Egg
                            addMessage("[Turn " + std::to_string(turnCount) + "] Ender Dragon dropped a Dragon Egg!"); // 记录掉落消息 / Log drop message
                            addMessage("[Turn " + std::to_string(turnCount) + "] You defeated the Ender Dragon! Victory!"); // 记录胜利消息 / Log victory message
                            gameOver = true; // 设置游戏结束（胜利） / Set game over (victory)
                        } else if (enemy->getName() == "Baby Zombie" && dropChance < 30) { // 如果是Baby Zombie且30%概率 / If Baby Zombie and 30% chance
                            player->addToInventory(new Item("Rotten Flesh", "Zombie's drop", 0, 0, 5)); // 添加腐肉 / Add Rotten Flesh
                            addMessage("[Turn " + std::to_string(turnCount) + "] Baby Zombie dropped Rotten Flesh!"); // 记录掉落消息 / Log drop message
                        }
                        creeperCountdown.erase(enemy); // 如果敌人是Creeper，移除其爆炸倒计时 / If enemy is Creeper, remove its explosion countdown
                        delete enemy; // 释放敌人内存 / Free enemy memory
                        enemies.erase(enemies.begin() + (target - 1)); // 从敌人列表移除 / Remove enemy from list
                    }
                    updateEnemySkills(); // 更新敌人技能（比如Creeper爆炸） / Update enemy skills (e.g., Creeper explosion)
                    if (!player->isAlive()) { // 如果玩家死亡 / If player is dead
                        addMessage("[Turn " + std::to_string(turnCount) + "] You died! Game Over!"); // 记录死亡消息 / Log death message
                        gameOver = true; // 设置游戏结束（失败） / Set game over (failure)
                    }
                }
            }
            break; // 结束此选项 / End this option
        case 7: // 选项7：装备或使用物品 / Option 7: Equip or use item
            {
                player->displayInventory(); // 显示玩家背包内容 / Display player's inventory
                std::cout << "Enter item number to equip/use: "; // 提示输入物品编号 / Prompt for item number
                int index; // 定义变量存储物品编号 / Define variable to store item number
                while (true) { // 进入循环，直到输入有效 / Enter loop until valid input
                    std::getline(std::cin, input); // 读取用户输入 / Read user input
                    if (validateInput(input, index, player->getInventory().size())) break; // 如果输入有效，退出循环 / If input is valid, exit loop
                    std::cout << "Invalid input! Please enter a number between 1 and " << player->getInventory().size() << ": "; // 提示重新输入 / Prompt to retry
                }
                if (index > 0) { // 如果输入的编号大于0（有效） / If entered number is greater than 0 (valid)
                    player->equipItem(index - 1); // 装备或使用物品（编号从1开始，索引从0开始） / Equip or use item (number starts at 1, index at 0)
                    if (index <= player->getInventory().size()) { // 如果物品存在 / If item exists
                        addMessage("[Turn " + std::to_string(turnCount) + "] Equipped/Used " + player->getInventory()[index - 1]->name + "!"); // 记录装备/使用消息 / Log equip/use message
                    }
                } else { // 如果输入无效编号 / If invalid number entered
                    addMessage("[Turn " + std::to_string(turnCount) + "] Invalid item number!"); // 记录无效消息 / Log invalid message
                }
            }
            break; // 结束此选项 / End this option
        case 8: // 选项8：保存游戏 / Option 8: Save game
            saveGame(); // 调用保存游戏函数 / Call save game function
            addMessage("[Turn " + std::to_string(turnCount) + "] Game saved!"); // 记录保存消息 / Log save message
            break; // 结束此选项 / End this option
        case 9: // 选项9：退出游戏 / Option 9: Exit game
            addMessage("[Turn " + std::to_string(turnCount) + "] Game exited."); // 记录退出消息 / Log exit message
            gameOver = true; // 设置游戏结束 / Set game over
            break; // 结束此选项 / End this option
        case 10: // 选项10：切换玩家状态显示 / Option 10: Toggle player status display
            showPlayerStatus = !showPlayerStatus; // 切换状态（显示/隐藏） / Toggle status (show/hide)
            addMessage("[Turn " + std::to_string(turnCount) + "] Player status display " + std::string(showPlayerStatus ? "enabled" : "disabled")); // 记录切换消息 / Log toggle message
            break; // 结束此选项 / End this option
        case 11: // 选项11：切换背包显示 / Option 11: Toggle inventory display
            showInventory = !showInventory; // 切换背包（显示/隐藏） / Toggle inventory (show/hide)
            addMessage("[Turn " + std::to_string(turnCount) + "] Inventory display " + std::string(showInventory ? "enabled" : "disabled")); // 记录切换消息 / Log toggle message
            break; // 结束此选项 / End this option
    }
    if (choice >= 1 && choice <= 4 && oldRoom != rooms[0]) { // 如果选择了移动（1-4）且旧房间不是The End / If movement chosen (1-4) and old room isn't The End
        delete oldRoom; // 释放旧房间的内存 / Free memory for old room
    }
    return true; // 返回true，继续游戏循环 / Return true to continue game loop
}

// 运行游戏：主循环，持续显示界面和处理输入直到游戏结束 / Run game: Main loop, keep displaying interface and handling input until game ends
void Game::run() {
    while (!gameOver && player->isAlive()) { // 检查游戏未结束且玩家存活 / Check game not over and player alive
        displayInterface(); // 显示游戏界面 / Display game interface
        if (!handleInput()) { // 如果输入处理失败（比如玩家已死） / If input handling fails (e.g., player dead)
            continue; // 跳到下一次循环 / Skip to next iteration
        }
    }
    clearScreen(); // 清空屏幕，准备显示游戏结束画面 / Clear screen to show game over screen
    const int WIDTH = 78; // 定义结束界面的内部宽度 / Define inner width for game over screen
    const std::string BORDER = std::string(80, '-'); // 定义边框线，80个横杠 / Define border line with 80 dashes
    std::cout << BORDER << "\n"; // 打印顶部边框 / Print top border
    std::string endTitle = !player->isAlive() ? " Game Over - You Died " : " Game Over - Victory "; // 根据死亡或胜利设置标题 / Set title based on death or victory
    std::cout << "| " << centerWithDashes(endTitle, WIDTH) << " |\n"; // 打印标题，居中 / Print title, centered
    for (const auto& msg : messageLog) { // 遍历消息日志 / Loop through message log
        std::string formattedMsg = msg; // 复制消息 / Copy message
        while (formattedMsg.length() > WIDTH) { // 如果消息太长 / If message is too long
            std::cout << "| " << padContent(formattedMsg.substr(0, WIDTH), WIDTH) << " |\n"; // 打印前半部分 / Print first part
            formattedMsg = "  " + formattedMsg.substr(WIDTH); // 剩余部分加两个空格缩进 / Remaining part with two-space indent
        }
        std::cout << "| " << padContent(formattedMsg, WIDTH) << " |\n"; // 打印消息 / Print message
    }
    std::cout << BORDER << "\n"; // 打印底部边框 / Print bottom border
}